package com.raft.core.rpc.nio;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.concurrent.ThreadSafe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.raft.core.node.NodeId;

import io.netty.channel.ChannelFutureListener;

/**记录来自远程节点的所有连接，并且在当前节点变成leader节点时重置所有入口连接，即关闭所有入口连接
 * @author zhangsulei
 *
 */
@ThreadSafe
class InboundChannelGroup {

    private static final Logger logger = LoggerFactory.getLogger(InboundChannelGroup.class);
    private final List<NioChannel> channels = new CopyOnWriteArrayList<>();

    /**增加入口连接
     * @param remoteId
     * @param channel
     */
    public void add(NodeId remoteId, NioChannel channel) {
        logger.info("channel INBOUND-{} connected", remoteId);
        // 连接关闭时移除
        channel.getDelegate().closeFuture().addListener((ChannelFutureListener) future -> {
            logger.info("channel INBOUND-{} disconnected", remoteId);
            remove(channel);
        });
    }

    private void remove(NioChannel channel) {
        channels.remove(channel);
    }

    void closeAll() {
        logger.info("close all inbound channels");
        for (NioChannel channel : channels) {
            channel.close();
        }
    }

}
